package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service(interfaceClass =MenuService.class )
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Map> findMenuByUserName(String username) {
        List<Map> list=menuMapper.findMenuByUserName(username);
        ArrayList<String> children = new ArrayList<>();
        for (Map map : list) {
            String icon = (String) map.get("icon");
            List<Map> childrens=menuMapper.findMenuByIcon(icon);
            for (Map children1 : childrens) {
                children1.put("children",children);
            }
            map.put("children",childrens);
        }
        return list;
    }
    @Override
    public PageResult findPage(Integer pageSize, String queryString, Integer currentPage) {
        //使用mybatis的分页插件
        PageHelper.startPage(currentPage, pageSize);
        //条件查询分页数据
        List<Menu> menuList = menuMapper.findGroupByCondition(queryString);
        //将查询出来的数据进行包装
        PageInfo<Menu> pageInfo = new PageInfo<>(menuList);
        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());
        return pageResult;
    }

    @Override
    public List<Role> findAll() {
        return menuMapper.findAll();
    }

    @Override
    public Menu findById(Integer id) {
        return menuMapper.findById(id);
    }

    @Override
    public List<Integer> findroleId(Integer id) {
        return menuMapper.findroleId(id);
    }

    @Override
    public void deleteById(Integer id) {
        Integer count = menuMapper.findCondition(id);
        if (count > 0) {
            throw new RuntimeException("菜单被角色引用,无法删除");
        }
        menuMapper.deleteById(id);
    }

    @Override
    public void edit(Integer[] roleIds, Menu menu) {
        menuMapper.deleteByMenuId(menu.getId());
        if (roleIds != null && roleIds.length > 0) {
            menuMapper.setMenuAndRole(roleIds, menu.getId());
        }
        menuMapper.edit(menu);
    }

    @Override
    public void addMenu(Integer[] roleIds, Menu menu) {
        menuMapper.addMenu(menu);
        if (roleIds!=null&&roleIds.length>0){
            menuMapper.setMenuAndRole(roleIds,menu.getId());
        }
    }
}
